package service

import (
	"errors"
	"gorm.io/gorm"
	"mime/multipart"
	"tdy-backend/app/core/service"
	"tdy-backend/app/member/dto"
	"tdy-backend/app/member/model"
	"tdy-backend/global"
	"tdy-backend/pkg/paginator"
	"tdy-backend/pkg/storage"
	"tdy-backend/utils"
)

type UploaderService struct {
	service.BaseService
}

//新增媒体
func (o *UploaderService) Add(file *multipart.FileHeader, uniqueKey string) (*model.Asset, error) {
	limitSize := global.TYD_CONFIG.GetInt64("file.limitSize")
	if file.Size > limitSize*1024*1024 {
		return nil, errors.New(file.Filename + "，此文件超出限制大小")
	}
	mimeType := utils.GetFileType(file.Header["Content-Type"][0])
	if mimeType == 0 {
		return nil, errors.New(file.Filename + ",此上传的文件类型不支持")
	}

	asset := model.Asset{}
	db := global.TYD_DB
	asset.Name = file.Filename
	asset.UniqueKey = uniqueKey
	asset.MemberId = o.MemberInfo.ID
	asset.Size = file.Size
	asset.Type = mimeType
	asset.FileType = file.Header["Content-Type"][0]
	db.Create(&asset)
	asset.UniqueKeyPreview = storage.GetUrl(asset.UniqueKey)
	return &asset, nil
}

//删除媒体
func (o *UploaderService) Delete(param dto.AssetDeleteDto) error {
	asset := []model.Asset{}
	db := global.TYD_DB
	assetInfo := db.Where("id IN ?", param.Ids).Where("member_id=?", o.MemberInfo.ID).Find(&asset)
	if assetInfo.RowsAffected == 0 {
		return errors.New("媒体文件不存在")
	}
	db.Delete(&asset)
	return nil
}

//编辑媒体
func (o *UploaderService) Edit(param dto.AssetEditDto) error {
	asset := model.Asset{}
	db := global.TYD_DB
	assetInfo := db.Where("id=?", param.ID).Where("member_id=?", o.MemberInfo.ID).First(&asset)
	if errors.Is(assetInfo.Error, gorm.ErrRecordNotFound) {
		return errors.New("媒体文件不存在")
	}
	asset.Name = param.Name
	db.Select("name").Save(&asset)
	return nil
}

//分页媒体
func (o *UploaderService) ListForPage(param dto.AssetListDto) *paginator.Pagination {
	db := global.TYD_DB.Model(&model.Asset{})
	assetList := []model.Asset{}
	if param.Keyword != "" {
		db = db.Where("name like ?", "%"+param.Keyword+"%")
	}
	if param.Type > 0 {
		db = db.Where("type = ?", param.Type)
	}
	db = db.Where("member_id=?", o.MemberInfo.ID)

	var total int64
	db.Count(&total)
	db.Scopes(paginator.Paginate(&param.PageParam)).Order("id desc").Find(&assetList)
	result := &paginator.Pagination{}
	result.Page = param.Page
	result.PageSize = param.PageSize
	result.Total = total
	for k, asset := range assetList {
		assetList[k].UniqueKeyPreview = storage.GetUrl(asset.UniqueKey)
	}
	result.Data = assetList

	return result
}
